package exttable.formgenerator;

import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import dbutils.DbUtils;
import exttable.SGTTestParametrs;
import exttable.dbclasses.*;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 28.05.11
 * Time: 15:46
 * To change this template use File | Settings | File Templates.
 */
public class InsertProbationerForm {
    JFrame frame;
    JPanel panel;
    SpringLayout mainLayout;
    JLabel labelProbationerCode;
    JTextField jtfProbationerCode;
    JLabel labelGroup;
    JTextField jtfGroupCode;
    JLabel labelDateVisitZero;
    JPanel datePanel;
    JLabel labelExcluded;
    JPanel excludedPanel;
    JRadioButton rbExcludedYes;
    JRadioButton rbExcludedNo;
    ButtonGroup bgExcluded;
    JLabel labelSavetButton;
    JButton saveButton;
    Group group;


//    public InsertProbationerForm(final ProbationersGroupsV1 probationersGroups) {
    public InsertProbationerForm(final ProbationersGroupsV2 probationersGroups) {
//        group = ProbationersGroupsV1.getGroupToProbationer(probationersGroups);
        group = ProbationersGroupsV2.getGroupToProbationer(probationersGroups);
        frame = new JFrame();
        panel = new JPanel();
        labelProbationerCode = new JLabel(Localisation.getMessage("menu.probationer"));
        jtfProbationerCode = new JTextField(probationersGroups.getProbationerCode());
        jtfProbationerCode.setEnabled(false);
        jtfProbationerCode.setColumns(8);
        labelGroup = new JLabel(Localisation.getMessage("table.column.groupcode"));
        jtfGroupCode = new JTextField();
        jtfGroupCode.setText(group.getGroupCode());
        jtfGroupCode.setEnabled(false);
        jtfGroupCode.setColumns(group.getGroupCode().length());
        labelDateVisitZero = new JLabel(Localisation.getMessage("labelDateVisitZero"));
        datePanel = StaticMethods.getCalendarPanel("date_visit_zero");
        labelExcluded = new JLabel(Localisation.getMessage("labelExcluded"));
        rbExcludedYes = new JRadioButton(Localisation.getMessage("form.yes"));
        rbExcludedNo = new JRadioButton(Localisation.getMessage("form.no"));
        rbExcludedNo.setSelected(true);
        bgExcluded = new ButtonGroup();
        bgExcluded.add(rbExcludedYes);
        bgExcluded.add(rbExcludedNo);
        excludedPanel = new JPanel();
        excludedPanel.add(rbExcludedYes);
        excludedPanel.add(rbExcludedNo);
        panel.add(labelProbationerCode);
        panel.add(jtfProbationerCode);
        panel.add(labelGroup);
        panel.add(jtfGroupCode);
        panel.add(labelDateVisitZero);
        panel.add(datePanel);
        panel.add(labelExcluded);
        panel.add(excludedPanel);
        labelSavetButton = new JLabel();
        panel.add(labelSavetButton);
        saveButton = new JButton(Localisation.getMessage("error.save"));
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (StaticMethods.getJFormattedTextFieldOfCalendarPanel(datePanel).getText().equals("")) {
                    MessageFactory.emptyFields();
                    datePanel.getComponent(0).setBackground(Color.RED);
                    return;
                }
                if (MessageFactory.isToSave()) {
                    try {
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    StaticMethods.getProgressFrame("createProbationer", Localisation.getMessage("processRunning"));
                                    Connection connGeneral = null;
                                    PreparedStatement psGeneralProbationersGroups = null;
                                    PreparedStatement psGeneralProbationers = null;

                                    Connection connSecondary = null;
                                    PreparedStatement psSecondaryProbationersGroups = null;
                                    PreparedStatement psSecondaryProbationers = null;

                                    String queryProbationersGroups = "INSERT INTO probationers_groups VALUES( '" +
                                            probationersGroups.getProbationerCode() + "'," +
                                            group.getGroupId() + "," +
                                            StaticMethods.convertBooleanToInt(rbExcludedYes.isSelected()) + "," +
                                            probationersGroups.getSexId() + "," +
                                            probationersGroups.getDegreeOfInflammatoryId() + "," +
                                            probationersGroups.getProcessByLocalizationId() + "," +
                                            StaticMethods.convertBooleanToInt(probationersGroups.isDiseaseDurationMoreThenYear()) + "," +
                                            StaticMethods.convertBooleanToInt(probationersGroups.isAlcoholic()) + "," +
                                            StaticMethods.convertBooleanToInt(probationersGroups.isNarcomaniac()) + ");";

                                    String queryProbationers = "INSERT INTO probationers(probationer_id, volunteer_id, probationer_code, group_id, date_visit_zero, excluded, user, insert_datetime)" +
                                            " VALUES(NULL, " +
                                            probationersGroups.getVolunteerId() + ",'" +
                                            probationersGroups.getProbationerCode() + "'," +
                                            group.getGroupId() + ",'" +
                                            StaticMethods.returnFormatedData(StaticMethods.getJFormattedTextFieldOfCalendarPanel(datePanel).getText()) + "'," +
                                            StaticMethods.convertBooleanToInt(rbExcludedYes.isSelected()) + ",'" +
                                            SGTTestParametrs.getInstance().getUserName() + "','" +
                                            StaticMethods.returnFormattedDataFromDate(new Date()) + "');";
                                    connGeneral = DbUtils.getDBConnectionGeneral();
                                    psGeneralProbationersGroups = connGeneral.prepareStatement(queryProbationersGroups);
                                    psGeneralProbationers = connGeneral.prepareStatement(queryProbationers);

                                    connSecondary = DbUtils.getDBConnectionSecondary();
                                    psSecondaryProbationersGroups = connSecondary.prepareStatement(queryProbationersGroups);
                                    psSecondaryProbationers = connSecondary.prepareStatement(queryProbationers);

                                    if (psGeneralProbationersGroups.executeUpdate() > 0 && psGeneralProbationers.executeUpdate() > 0) {
                                        if(DbUtils.mapDataBases.get(DbUtils.SECONDARY_DATABASE_NAME)!=null){
                                            psSecondaryProbationersGroups.executeUpdate();
                                            psSecondaryProbationers.executeUpdate();
                                        }
                                        StaticMethods.getFrameByName("createProbationer").dispose();
                                        JOptionPane.showMessageDialog(null, Localisation.getMessage("info.dataadded"), "", JOptionPane.INFORMATION_MESSAGE);
                                        frame.dispose();
                                    }
                                    connGeneral.close();
                                } catch (MySQLIntegrityConstraintViolationException excep) {
                                    StaticMethods.getFrameByName("createProbationer").dispose();
                                    JOptionPane.showMessageDialog(null, ComponentsToPanel.getDuplicateMessage(excep.getMessage()), "error",
                                            JOptionPane.ERROR_MESSAGE);
                                    excep.printStackTrace();
                                } catch (Exception excep) {
                                    StaticMethods.getFrameByName("createProbationer").dispose();
                                    JOptionPane.showMessageDialog(null, Localisation.getMessage("error.applicationerror"), "error",
                                            JOptionPane.ERROR_MESSAGE);
                                    excep.printStackTrace();
                                }
                            }
                        });
                        thread.start();

                    } catch (Exception exp) {
                        exp.printStackTrace();
                        StaticMethods.getFrameByName("createProbationer").dispose();
                    }
                }

            }
        });
        panel.add(saveButton);
        mainLayout = new SpringLayout();
        panel.setLayout(mainLayout);
        organiseLayout();
        frame.add(panel);
        frame.setSize(500, 300);
        frame.setVisible(true);
    }

    private void organiseLayout() {

        mainLayout.putConstraint(SpringLayout.WEST, labelProbationerCode, 20, SpringLayout.WEST, panel);
        mainLayout.putConstraint(SpringLayout.NORTH, labelProbationerCode, 10, SpringLayout.NORTH, panel);
        mainLayout.putConstraint(SpringLayout.WEST, jtfProbationerCode, 100, SpringLayout.EAST, labelProbationerCode);
        mainLayout.putConstraint(SpringLayout.NORTH, jtfProbationerCode, 10, SpringLayout.NORTH, panel);

        mainLayout.putConstraint(SpringLayout.WEST, labelGroup, 20, SpringLayout.WEST, panel);
        mainLayout.putConstraint(SpringLayout.NORTH, labelGroup, 20, SpringLayout.SOUTH, labelProbationerCode);
        mainLayout.putConstraint(SpringLayout.WEST, jtfGroupCode, 0, SpringLayout.WEST, jtfProbationerCode);
        mainLayout.putConstraint(SpringLayout.NORTH, jtfGroupCode, 20, SpringLayout.SOUTH, jtfProbationerCode);

        mainLayout.putConstraint(SpringLayout.WEST, labelDateVisitZero, 20, SpringLayout.WEST, panel);
        mainLayout.putConstraint(SpringLayout.NORTH, labelDateVisitZero, 20, SpringLayout.SOUTH, jtfGroupCode);
        mainLayout.putConstraint(SpringLayout.WEST, datePanel, 0, SpringLayout.WEST, jtfGroupCode);
        mainLayout.putConstraint(SpringLayout.NORTH, datePanel, 20, SpringLayout.SOUTH, jtfGroupCode);

        mainLayout.putConstraint(SpringLayout.WEST, labelExcluded, 20, SpringLayout.WEST, panel);
        mainLayout.putConstraint(SpringLayout.NORTH, labelExcluded, 20, SpringLayout.SOUTH, datePanel);
        mainLayout.putConstraint(SpringLayout.WEST, excludedPanel, 0, SpringLayout.WEST, datePanel);
        mainLayout.putConstraint(SpringLayout.NORTH, excludedPanel, 20, SpringLayout.SOUTH, datePanel);

        mainLayout.putConstraint(SpringLayout.WEST, labelSavetButton, 20, SpringLayout.WEST, panel);
        mainLayout.putConstraint(SpringLayout.NORTH, labelSavetButton, 20, SpringLayout.SOUTH, excludedPanel);
        mainLayout.putConstraint(SpringLayout.WEST, saveButton, 0, SpringLayout.WEST, excludedPanel);
        mainLayout.putConstraint(SpringLayout.NORTH, saveButton, 20, SpringLayout.SOUTH, excludedPanel);
    }
}
